<?php

namespace app\home\model\order;

use basic\BaseModel;
use services\PHPExcelService;
use think\facade\Db;

/**
 * 商品的订单模型
 * Class StoreOrder
 * @package app\home\model\order
 */
class StoreOrder extends BaseModel
{
    /**
     * 主键的ID
     * @var string
     */
    protected $pk = "id";

    /**
     * 模型的名称
     * @var string
     */
    protected $name = "store_order";

    /**
     * 获取最后一个月已支付的订单
     * @param int $is_promoter
     * @return int|string
     */
    public static function getOrderPayMonthCount($is_promoter = 0)
    {
        return self::where('o.paid', 1)->alias('o')->whereTime('o.pay_time', 'last month')->join('User u', 'u.uid=o.uid')->where('u.is_promoter', $is_promoter)->count();
    }

    /**
     * 获取已支付的订单
     * @param int $is_promoter
     * @return int|string
     */
    public static function getOrderPayCount($is_promoter = 0)
    {
        return self::where('o.paid', 1)->alias('o')->join('User u', 'u.uid=o.uid')->where('u.is_promoter', $is_promoter)->count();
    }

    /**
     * 条件切割
     * @param string $order
     * @param string $file
     * @return string
     */
    public static function setOrder($order, $file = '-')
    {
        if (empty($order)) return '';
        return str_replace($file, ' ', $order);
    }

    /**
     * 设置订单的状态
     * @param $status
     * @param null $model
     * @param string $alert
     * @return StoreOrder
     */
    public static function statusByWhere($status, $model = null, $alert = '')
    {
        if ($model == null) $model = (new self)->where("wxapp_id", self::$wxapp_id);
        if ('' === $status)
            return $model;
        else if ($status == 8)
            return $model;
        else if ($status == 0)//未支付
            return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
        else if ($status == 1)//已支付 未发货
            return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'shipping_type', 1)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
        else if ($status == 2)//已支付  待收货
            return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'shipping_type', 1)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
        else if ($status == 5)//已支付  待核销
            return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'shipping_type', 2)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
        else if ($status == 3)// 已支付  已收货  待评价
            return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
        else if ($status == 4)// 交易完成
            return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
        else if ($status == -1)//退款中
            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1)->where($alert . 'is_del', 0);
        else if ($status == -2)//已退款
            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2)->where($alert . 'is_del', 0);
        else if ($status == -3)//退款
            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2')->where($alert . 'is_del', 0);
        else if ($status == -4)//已删除
            return $model->where($alert . 'is_del', 1);
        else
            return $model;
    }

    /**
     * 处理where条件
     * @param $where
     * @param $model
     * @param string $aler
     * @param string $join
     * @return mixed
     */
    public static function getOrderWhere($where, $model, $aler = '', $join = '')
    {
        $model = $model->where('is_system_del', 0);
        if (isset($where['status']) && $where['status'] != '') {
            $model = self::statusByWhere($where['status'], $model, $aler);
        }
        if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
        if (isset($where['combination_id'])) {
            if ($where['combination_id'] == '普通订单') {
                $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
            }
            if ($where['combination_id'] == '拼团订单') {
                $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
            }
            if ($where['combination_id'] == '秒杀订单') {
                $model = $model->where($aler . 'seckill_id', ">", 0);
            }
            if ($where['combination_id'] == '砍价订单') {
                $model = $model->where($aler . 'bargain_id', ">", 0);
            }
        }
        if (isset($where['pay_type'])) {
            switch ($where['pay_type']) {
                case 1:
                    $model = $model->where($aler . 'pay_type', 'weixin');
                    break;
                case 2:
                    $model = $model->where($aler . 'pay_type', 'yue');
                    break;
                case 3:
                    $model = $model->where($aler . 'pay_type', 'offline');
                    break;
            }
        }
        if (isset($where['type'])) {
            switch ($where['type']) {
                case 1:
                    $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
                    break;
                case 2:
                    $model = $model->where($aler . 'combination_id', ">", 0);
                    break;
                case 3:
                    $model = $model->where($aler . 'seckill_id', ">", 0);
                    break;
                case 4:
                    $model = $model->where($aler . 'bargain_id', ">", 0);
                    break;
            }
        }

        if (isset($where['real_name']) && $where['real_name'] != '') {
            $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid|' . $join . '.phone' : ''), 'LIKE', "%$where[real_name]%");
        }
        if (isset($where['data']) && $where['data'] !== '') {
            $model = self::getModelTime($where, $model, $aler . 'add_time');
        }
        return $model;
    }

    /**
     * 获取时间段之间的model
     * @param $where
     * @param null $model
     * @param string $prefix
     * @param string $data
     * @param string $field
     * @return StoreOrder
     */
    public static function getModelTime($where, $model = null, $prefix = 'add_time', $data = 'data', $field = ' - ')
    {
        if ($model == null) $model = new self;
        if (!isset($where[$data])) return $model;
        switch ($where[$data]) {
            case 'today':
            case 'week':
            case 'month':
            case 'year':
            case 'yesterday':
                $model = $model->whereTime($prefix, $where[$data]);
                break;
            case 'quarter':
                list($startTime, $endTime) = self::getMonth();
                $model = $model->where($prefix, '>', strtotime($startTime));
                $model = $model->where($prefix, '<', strtotime($endTime));
                break;
            case 'lately7':
                $model = $model->where($prefix, 'between', [strtotime("-7 day"), time()]);
                break;
            case 'lately30':
                $model = $model->where($prefix, 'between', [strtotime("-30 day"), time()]);
                break;
            default:
                if (strstr($where[$data], $field) !== false) {
                    list($startTime, $endTime) = explode($field, $where[$data]);
                    $model = $model->where($prefix, '>', strtotime($startTime));
                    $model = $model->where($prefix, '<', bcadd(strtotime($endTime), 86400, 0));
                }
                break;
        }
        return $model;
    }

    /**
     * 订单的数量的统计
     * @return mixed
     */
    public static function orderCount()
    {
        $data['wz'] = self::statusByWhere(0, new self())->where(['is_system_del' => 0])->count();
        $data['wf'] = self::statusByWhere(1, new self())->where(['is_system_del' => 0, 'shipping_type' => 1])->count();
        $data['ds'] = self::statusByWhere(2, new self())->where(['is_system_del' => 0, 'shipping_type' => 1])->count();
        $data['dp'] = self::statusByWhere(3, new self())->where(['is_system_del' => 0])->count();
        $data['jy'] = self::statusByWhere(4, new self())->where(['is_system_del' => 0])->count();
        $data['tk'] = self::statusByWhere(-1, new self())->where(['is_system_del' => 0])->count();
        $data['yt'] = self::statusByWhere(-2, new self())->where(['is_system_del' => 0])->count();
        $data['del'] = self::statusByWhere(-4, new self())->where(['is_system_del' => 0])->count();
        $data['write_off'] = self::statusByWhere(5, new self())->where(['is_system_del' => 0])->count();
        $data['general'] = self::where(['pink_id' => 0, 'combination_id' => 0, 'seckill_id' => 0, 'bargain_id' => 0, 'is_system_del' => 0])->count();
        $data['pink'] = self::where('pink_id|combination_id', '>', 0)->where('is_system_del', 0)->count();
        $data['seckill'] = self::where('seckill_id', '>', 0)->where('is_system_del', 0)->count();
        $data['bargain'] = self::where('bargain_id', '>', 0)->where('is_system_del', 0)->count();
        return $data;
    }


    /**
     * 获取类型的统计
     * @return array
     */
    public static function payTypeCount()
    {
        $where['status'] = 8;
        $where['is_del'] = 0;
        $where['real_name'] = '';
        $where['data'] = '';
        $where['type'] = '';
        $where['order'] = '';
        $where['pay_type'] = 1;
        $where["wxapp_id"] = self::$wxapp_id;
        $weixin = self::getOrderWhere($where, new self)->count();
        $where['pay_type'] = 2;
        $yue = self::getOrderWhere($where, new self)->count();
        $where['pay_type'] = 3;
        $offline = self::getOrderWhere($where, new self)->count();
        return compact('weixin', 'yue', 'offline');
    }

    /**
     * @param array $where
     */
    public static function OrderList($where)
    {
        $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.*,r.nickname,r.phone,r.spread_uid')->where("a.wxapp_id", self::$wxapp_id);
        if ($where['order'] != '') {
            $model = $model->order(self::setOrder($where['order']));
        } else {
            $model = $model->order('a.id desc');
        }
        if (isset($where['excel']) && $where['excel'] == 1) {
            $data = ($data = $model->select()) && count($data) ? $data->toArray() : [];
        } else {
            $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
        }

        foreach ($data as &$item) {
            $_info = Db::name('store_order_cart_info')->where('oid', $item['id'])->field('cart_info')->select();
            $_info = count($_info) ? $_info->toArray() : [];
            foreach ($_info as $k => $v) {
                $cart_info = json_decode($v['cart_info'], true);
                if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
                $_info[$k]['cart_info'] = $cart_info;
                unset($cart_info);
            }
            $item['_info'] = $_info;
            $item['spread_nickname'] = Db::name('user')->where('uid', $item['spread_uid'])->value('nickname');
            $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
            $item['back_integral'] = $item['back_integral'] ?: 0;
            if ($item['pink_id'] || $item['combination_id']) {
                $pinkStatus = 1;
                switch ($pinkStatus) {
                    case 1:
                        $item['pink_name'] = '[拼团订单]正在进行中';
                        $item['color'] = '#f00';
                        break;
                    case 2:
                        $item['pink_name'] = '[拼团订单]已完成';
                        $item['color'] = '#00f';
                        break;
                    case 3:
                        $item['pink_name'] = '[拼团订单]未完成';
                        $item['color'] = '#f0f';
                        break;
                    default:
                        $item['pink_name'] = '[拼团订单]历史订单';
                        $item['color'] = '#457856';
                        break;
                }
            } elseif ($item['seckill_id']) {
                $item['pink_name'] = '[秒杀订单]';
                $item['color'] = '#32c5e9';
            } elseif ($item['bargain_id']) {
                $item['pink_name'] = '[砍价订单]';
                $item['color'] = '#12c5e9';
            } else {
                if ($item['shipping_type'] == 1) {
                    $item['pink_name'] = '[普通订单]';
                    $item['color'] = '#895612';
                } else if ($item['shipping_type'] == 2) {
                    $item['pink_name'] = '[核销订单]';
                    $item['color'] = '#8956E8';
                }
            }
            if ($item['paid'] == 1) {
                switch ($item['pay_type']) {
                    case 'weixin':
                        $item['pay_type_name'] = '微信支付';
                        break;
                    case 'yue':
                        $item['pay_type_name'] = '余额支付';
                        break;
                    case 'offline':
                        $item['pay_type_name'] = '线下支付';
                        break;
                    default:
                        $item['pay_type_name'] = '其他支付';
                        break;
                }
            } else {
                switch ($item['pay_type']) {
                    default:
                        $item['pay_type_name'] = '未支付';
                        break;
                    case 'offline':
                        $item['pay_type_name'] = '线下支付';
                        $item['pay_type_info'] = 1;
                        break;
                }
            }
            if ($item['paid'] == 0 && $item['status'] == 0) {
                $item['status_name'] = '未支付';
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
                $item['status_name'] = '未发货';
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '未核销';
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
                $item['status_name'] = '待收货';
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '未核销';
            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '待评价';
            } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
                $item['status_name'] = '已完成';
            } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
                $refundReasonTime = date('Y-m-d H:i', $item['refund_reason_time']);
                $refundReasonWapImg = json_decode($item['refund_reason_wap_img'], true);
                $refundReasonWapImg = $refundReasonWapImg ? $refundReasonWapImg : [];
                $img = '';
                if (count($refundReasonWapImg)) {
                    foreach ($refundReasonWapImg as $itemImg) {
                        if (strlen(trim($itemImg)))
                            $img .= '<img style="height:50px;" src="' . $itemImg . '" />';
                    }
                }
                if (!strlen(trim($img))) $img = '无';
                if (isset($where['excel']) && $where['excel'] == 1) {
                    $refundImageStr = implode(',', $refundReasonWapImg);
                    $item['status_name'] = <<<TEXT
退款原因:{$item['refund_reason_wap']} 
备注说明：{$item['refund_reason_wap_explain']}
退款时间：{$refundReasonTime}
凭证连接：{$refundImageStr}
TEXT;
                    unset($refundImageStr);
                } else {
                    $item['status_name'] = <<<HTML
<b style="color:#f124c7">申请退款</b><br/>
<span>退款原因：{$item['refund_reason_wap']}</span><br/>
<span>备注说明：{$item['refund_reason_wap_explain']}</span><br/>
<span>退款时间：{$refundReasonTime}</span><br/>
<span>退款凭证：{$img}</span>
HTML;
                }
            } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
                $item['status_name'] = '已退款';
            }
            if ($item['paid'] == 0 && $item['status'] == 0 && $item['refund_status'] == 0) {
                $item['_status'] = 1;
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
                $item['_status'] = 2;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
                $item['_status'] = 3;
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
                $item['_status'] = 4;
            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
                $item['_status'] = 5;
            } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
                $item['_status'] = 6;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
                $item['_status'] = 7;
            }
        }
        if (isset($where['excel']) && $where['excel'] == 1) {
            self::SaveExcel($data);
        }
        $count = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->where("a.wxapp_id", self::$wxapp_id)->count();
        return compact('count', 'data');
    }

    /**
     * 保存Excel数据
     * @param $list
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public static function SaveExcel($list)
    {
        $export = [];
        foreach ($list as $index => $item) {
            $_info = Db::name('store_order_cart_info')->where('oid', $item['id'])->column('cart_info');
            $goodsName = [];
            foreach ($_info as $k => $v) {
                $v = json_decode($v, true);
                $goodsName[] = implode(
                    [$v['productInfo']['store_name'],
                        isset($v['productInfo']['attrInfo']) ? '(' . $v['productInfo']['attrInfo']['suk'] . ')' : '',
                        "[{$v['cart_num']} * {$v['truePrice']}]"
                    ], ' ');
            }
            $item['cartInfo'] = $_info;
            $sex = Db::name('wechat_user')->where('uid', $item['uid'])->value('sex');
            if ($sex == 1) $sex_name = '男';
            else if ($sex == 2) $sex_name = '女';
            else $sex_name = '未知';
            $export[] = [
                $item['order_id'],
                $sex_name,
                $item['phone'],
                $item['real_name'],
                $item['user_phone'],
                $item['user_address'],
                $goodsName,
                $item['total_price'],
                $item['pay_price'],
                $item['pay_postage'],
                $item['coupon_price'],
                $item['pay_type_name'],
                $item['pay_time'] > 0 ? date('Y/m-d H:i', $item['pay_time']) : '暂无',
                $item['status_name'],
                $item['add_time'],
                $item['mark']
            ];
        }
        PHPExcelService::setExcelHeader(['订单号', '性别', '电话', '收货人姓名', '收货人电话', '收货地址', '商品信息',
            '总价格', '实际支付', '邮费', '优惠金额', '支付状态', '支付时间', '订单状态', '下单时间', '用户备注'])
            ->setExcelTile('订单导出' . date('YmdHis', time()), '订单信息' . time(), ' 生成时间：' . date('Y-m-d H:i:s', time()))
            ->setExcelContent($export)
            ->ExcelSave();
    }


    public static function getOrderPrice(array $where)
    {
    }

    /**
     * 获取用户的支付的金额
     * @param int $uid
     * @return int
     */
    public static function getUserCountPay($uid = 0)
    {
        if (!$uid) return 0;
        return self::where('uid', $uid)->where('paid', 1)->count();
    }
}